#include "setmrtsconfig.h"
#include "ui_setmrtsconfig.h"
#include <QApplication>
#include <QtWidgets>
#include <QXmlStreamWriter>
#include "iostream"
#include "unistd.h"
#include <QtWidgets>
#include <QXmlStreamWriter>
#include <dbutils.h>
#include <QSqlQuery>
#include <QChart>
#include <QChartView>
#include <QLineSeries>
#include <QCategoryAxis>
using namespace std;
QVector<QString> algorithms;
QStringList rrr_min_list,rrr_max_list;
QString fileDir;
setmrtsConfig::setmrtsConfig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::setmrtsConfig)
{
    ui->setupUi(this);
}

setmrtsConfig::~setmrtsConfig()
{
    algorithms.clear();
    rrr_max_list.clear();
    rrr_min_list.clear();
    fileDir.clear();
    delete ui;
}


void setmrtsConfig::generateXmlFromInputFields(QWidget* window)
{
    // 创建一个XML文件
    QFile file("/home/huwei/SET-MRTS-master/config.xml");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        qDebug() << "无法打开文件进行写入";
        return;
    }


    QXmlStreamWriter xmlWriter(&file);
    xmlWriter.setAutoFormatting(true);

    xmlWriter.writeStartDocument();
    xmlWriter.writeStartElement("parameters");

    QList<QLineEdit*> lineEdits = window->findChildren<QLineEdit*>();


    QList<QComboBox*> comboBoxes = window->findChildren<QComboBox*>();

    QList<QGroupBox*> groupBoxes = window->findChildren<QGroupBox*>();
    foreach (QGroupBox* groupBox, groupBoxes) {
        QList<QDoubleSpinBox*> groupBoxDoubleSpinBoxes = groupBox->findChildren<QDoubleSpinBox*>();
        if (groupBoxDoubleSpinBoxes.size() == 1){
            QString childTagName = groupBoxDoubleSpinBoxes.at(0)->objectName();
            xmlWriter.writeStartElement(childTagName);//开标签
            xmlWriter.writeStartElement("data");//开data
            xmlWriter.writeCharacters(QString(groupBoxDoubleSpinBoxes.at(0)->text()));//写数据
            xmlWriter.writeEndElement();//关data
            xmlWriter.writeEndElement();//关标签
        }
        else if(groupBoxDoubleSpinBoxes.size()==2) {
            if(groupBoxDoubleSpinBoxes.at(0)->objectName().endsWith("_min")){
                QString childTagName = groupBoxDoubleSpinBoxes.at(0)->objectName().remove("_min");
                xmlWriter.writeStartElement(childTagName);//开标签
                xmlWriter.writeStartElement("data");//开data
                xmlWriter.writeStartElement("min");//开min
                xmlWriter.writeCharacters(QString(groupBoxDoubleSpinBoxes.at(0)->text()));
                xmlWriter.writeEndElement();//关min
                xmlWriter.writeStartElement("max");//开max
                xmlWriter.writeCharacters(QString(groupBoxDoubleSpinBoxes.at(1)->text()));
                xmlWriter.writeEndElement();//关max
                xmlWriter.writeEndElement();//关data
                xmlWriter.writeEndElement();//关标签
            }
            else if(groupBoxDoubleSpinBoxes.at(0)->objectName().endsWith("_max")){
                QString childTagName = groupBoxDoubleSpinBoxes.at(0)->objectName().remove("_max");
                xmlWriter.writeStartElement(childTagName);//开标签
                xmlWriter.writeStartElement("data");//开data
                xmlWriter.writeStartElement("min");//min
                xmlWriter.writeCharacters(QString(groupBoxDoubleSpinBoxes.at(1)->text()));
                xmlWriter.writeEndElement();//min
                xmlWriter.writeStartElement("max");//max
                xmlWriter.writeCharacters(QString(groupBoxDoubleSpinBoxes.at(0)->text()));
                xmlWriter.writeEndElement();//关max
                xmlWriter.writeEndElement();//关data
                xmlWriter.writeEndElement();//关标签
            }



        }


    }

    foreach(QLineEdit* edit,lineEdits){
        if(edit->objectName().startsWith("rrr")){

            if(edit->objectName()=="rrr_min"){
                rrr_min_list = ui->rrr_min->text().split(",");
            }
            else if (edit->objectName()=="rrr_max") {
                rrr_max_list = ui->rrr_max->text().split(",");
            }
        }
        else if(edit->objectName()!="qt_spinbox_lineedit"){
            QStringList dataList = edit->text().split(",");
            if (dataList.isEmpty()) {
                continue;
            }
            xmlWriter.writeStartElement(edit->objectName());
            foreach (const QString& data, dataList) {
                if(edit->objectName()=="server_ip"||edit->objectName()=="server_port"||edit->objectName()=="experiment_times"){
                    xmlWriter.writeCharacters(data.trimmed());
                    continue;
                }
                xmlWriter.writeStartElement("data");
                xmlWriter.writeCharacters(data.trimmed());
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndElement();
        }
    }
    xmlWriter.writeStartElement("rrr");//开标签
    for (int i = 0;i<rrr_max_list.size();i++ ) {
        xmlWriter.writeStartElement("data");//开data
        xmlWriter.writeStartElement("min");
        xmlWriter.writeCharacters(rrr_min_list.at(i));
        xmlWriter.writeEndElement();//min
        xmlWriter.writeStartElement("max");
        xmlWriter.writeCharacters(rrr_max_list.at(i));
        xmlWriter.writeEndElement();//max
        xmlWriter.writeEndElement();//关data
    }

    xmlWriter.writeEndElement();//关标签

    foreach(QComboBox* box,comboBoxes){
        xmlWriter.writeStartElement(box->objectName());
        xmlWriter.writeStartElement("data");
        xmlWriter.writeCharacters(box->currentText());
        xmlWriter.writeEndElement();
        xmlWriter.writeEndElement();
    }
    xmlWriter.writeStartElement("schedulability_test");
    foreach(QString str,algorithms){

        xmlWriter.writeStartElement("data");
        xmlWriter.writeCharacters(str);
        xmlWriter.writeEndElement();

    }
    xmlWriter.writeEndElement();

    // 结束写入文档
    xmlWriter.writeEndElement(); // 结束parameters元素
    xmlWriter.writeEndDocument();

    // 关闭文件
    file.close();

    qDebug() << "XML文件已生成";
}


void setmrtsConfig::on_xml_clicked()
{
    generateXmlFromInputFields(this);
    QString path = "/home/huwei/SET-MRTS-master/config.xml";
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open file.";

    }
    QTextStream stream(&file);
    stream.setAutoDetectUnicode(true);
    ui->xmlText->setText(stream.readAll());

    file.close();
}


void setmrtsConfig::on_schedulability_test_clicked()
{
    algorithmsItemUi.show();

}


void setmrtsConfig::on_analysis_clicked()
{
    fileDir = QString("/home/huwei/SET-MRTS-master/results/id[0]-M[%1]-P[%2]-rn[%3]-rrn[%4]-rrp[%5]-rrr[%6,%7]").arg(ui->mean->text()).arg(ui->processor_num->text())
            .arg(ui->resource_num->text()).arg(ui->rrn->text())
            .arg(ui->rrp->text()).arg(ui->rrr_min->text()).arg(ui->rrr_max->text());

    QDir folderDir("/home/huwei/SET-MRTS-master/results");

    if(folderDir.exists()){
        folderDir.removeRecursively();
        qDebug()<<"success remove folderDir "<<endl;
    }
    qDebug()<<fileDir<<endl;
    DBUtils *db = new DBUtils;
    QSqlQuery query;
    query.exec("delete from control_signal");
    query.clear();
    QString queryStr = QString("insert into control_signal (request_signal) values ('%1')").arg("startSchedule");
    cout<<queryStr.toStdString()<<endl;
    bool res =  query.exec(queryStr);
    if(res){
        cout<<"success"<<endl;
    }else{
        cout<<"error"<<endl;
    }

    delete db;
    QString originalPath = QDir::currentPath();
    QDir::setCurrent("/home/huwei/SET-MRTS-master");
    QProcess *processClient = new QProcess;
    processClient->start("./bt_client");
    sleep(1);
    QProcess *processServer = new QProcess;
    processServer->start("./bt_server");
    QDir::setCurrent(originalPath);

}





void setmrtsConfig::on_graph_clicked()
{
    drawGraph = new DrawGraph;
    drawGraph->show();
}




void setmrtsConfig::on_showTable_clicked()
{
    resultTable = new ResultTable;
    resultTable->show();
}
